package com.wisdytech.linkdcs.system.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.service.ISystemLoginManageService;
import com.wisdytech.linkdcs.system.vo.LoginVO;

/**
 * 
 * @author zhanghailin
 *
 */
@Service("systemLoginManageService")
@Transactional
public class SystemLoginManageServiceImpl implements ISystemLoginManageService{

	/**
	 * 获取登录用户信息分页
	 */
	@Override
	public StandardTableResult<LoginVO> getLoginUsers(String userName, String trueName, String ipAddress, Filter filter) {
		//处理session
		SessionsSecurityManager securityManager = (SessionsSecurityManager) SecurityUtils.getSecurityManager();
		DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager();
        Collection<Session> sessions=
        		sessionManager.getSessionDAO().getActiveSessions();//获取已登录的用户session列表
        List<LoginVO> loginVOList = new ArrayList<>();
        for (Session session : sessions) {
			LoginVO vo = new LoginVO();
			//获取登录用户信息
        	SysUser sessioUser= (SysUser)session.getAttribute("user");
			vo.setSessionId(session.getId());
			vo.setPkId(sessioUser.getPkId());
			vo.setIpAddress(session.getHost());
			vo.setUserName(sessioUser.getUsername());
	        vo.setTrueName(sessioUser.getTruename());
	        vo.setModuleName(String.valueOf(session.getAttribute("moduleName")));
	        vo.setLoginTime(session.getStartTimestamp());
	        //条件过滤
	        if(filterLoginVOByRequestParams(userName,trueName,ipAddress,vo)) {
	        	loginVOList.add(vo);
	        }
		}
        //对结果排序，时间逆序
        Collections.sort(loginVOList,new Comparator<LoginVO>() {
        	@Override
            public int compare(LoginVO o1, LoginVO o2) {
                // 返回值为int类型，大于0表示正序，小于0表示逆序
                return o2.getLoginTime().compareTo(o1.getLoginTime());
            }
		});
        //分页开始位置
        int start =(filter.getNum()==0?0:filter.getNum()-1)*filter.getSize();
        //分页结束位置
        int end = (start+filter.getSize())<=loginVOList.size()?(start+filter.getSize()):loginVOList.size();
        List<LoginVO> loginVOPageList = new ArrayList<>();
        //分页参数不正确返回空list
        if(start<=loginVOList.size()) {
        	for (int i = start; i < end; i++) {
            	loginVOPageList.add(loginVOList.get(i));
    		}
        }
		return new StandardTableResult<LoginVO>(loginVOList.size(),loginVOPageList);
	}
	
	
	/**
	 * 手动强制注销用户
	 */
	@Override
	public void logOffUserBySessionId(String sessionId) {
		//处理session
		SessionsSecurityManager securityManager = (SessionsSecurityManager) SecurityUtils.getSecurityManager();
		DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager();
		Session session = sessionManager.getSessionDAO().readSession(sessionId);
		if(session!=null) {
			//session立即失效
			//session.setTimeout(0);
			//删除session
			sessionManager.getSessionDAO().delete(session);
			//删除cache缓存
			//EhCacheManager cacheManager = (EhCacheManager)securityManager.getCacheManager();
			//cacheManager.getCache("shiro-activeSessionCache").remove(sessionId);
		}
	}
	

	/**
	 * 根据用户名剔除用户
	 */
	@Override
	public void logOffUserByUserName(String userName) {
		//处理session
		SessionsSecurityManager securityManager = (SessionsSecurityManager) SecurityUtils.getSecurityManager();
		DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager();
        Collection<Session> sessions=
        		sessionManager.getSessionDAO().getActiveSessions();//获取已登录的用户session列表
        for (Session session : sessions) {
			SysUser sysUser =(SysUser)session.getAttribute("user");
			if(sysUser!=null&&sysUser.getUsername().equals(userName)) {
				sessionManager.getSessionDAO().delete(session);
				//删除cache缓存
				EhCacheManager cacheManager = (EhCacheManager)securityManager.getCacheManager();
				cacheManager.getCache("shiro-activeSessionCache").remove(session.getId());
			}
		}
		
	}


	/**
	 * 返回list条件过滤
	 * @param userName
	 * @param trueName
	 * @param ipAddress
	 * @param loginVO
	 * @return
	 */
	private boolean filterLoginVOByRequestParams(String userName, String trueName, String ipAddress,LoginVO loginVO) {
		boolean flag = true;
		//username条件过滤
		if(StringUtils.isNotEmpty(userName)&&
				loginVO.getUserName().indexOf(userName)<0) {
			flag = false;
		}
		//truename条件过滤
		if(StringUtils.isNotEmpty(trueName)&&
				loginVO.getTrueName().indexOf(trueName)<0) {
			flag = false;
		}
		//ip地址过滤
		if(StringUtils.isNotEmpty(ipAddress)&&
				loginVO.getIpAddress().indexOf(ipAddress)<0) {
			flag = false;
		}
		return flag;
	}
}
